<?php

namespace common\handlers\backend;

use common\handlers\BaseHandler;
use yii\base\Event;
use yii\web\Cookie;

/**
 * 应用响应客户端请求时，添加自定义cookie！
 */
class BeforeResponseSetCookie extends BaseHandler
{
    const CLIENT_USER_PREFERENCE_COOKIE_NAME = 'user_preference';

    public function run($event)
    {
        $this->setUserPreferenceCookie($event);
    }

    /**
     * 设置用户偏好cookie
     * @param Event $event
     * @return void
     */
    public function setUserPreferenceCookie($event)
    {
        $identity = $this->user->identity;
        if (!$identity) {
            return;
        }

        /** @var \yii\web\Response $sender */
        $sender = $event->sender;
        if (empty($identity->user_preference)) {
            if ($this->request->getCookies()->has(self::CLIENT_USER_PREFERENCE_COOKIE_NAME)) {
                $sender->getCookies()->remove(self::CLIENT_USER_PREFERENCE_COOKIE_NAME);
            }
        } else {
            $sender->getCookies()->add(new Cookie([
                'httpOnly' => false,
                'name' => self::CLIENT_USER_PREFERENCE_COOKIE_NAME,
                'value' => $identity->user_preference,
                'expire' => time()+60*60*24*30, //设置过期时间为30天后。
            ]));
        }
    }
}